import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    batchNum: '',
    statusBarHeight: '',
    navBarHeight: '',
    searchValue: '',
    list: [],
    pageNum: 1,
    pageSize: 5,
    total: '',
    latitude: '',
    longitude: '',
    listType: 1,
    isSx: false,
    corpCredit: '',
    reservationNumber: '',
    filterList: [],
    labelList: [],
    searchObj: {},
    loading: true
  },
  openFi() {
    console.log(this.data.labelList, '筛选条件')
    let chaeckType = true
    if (this.data.labelList.length > 0) {
      chaeckType = true
    } else {
      chaeckType = false
    }
    this.setData({
      needFresh: false
    })
    wx.navigateTo({
      url: '/sub_qiangdan/kechuangfilter/kechuangfilter?chaeckType=' + chaeckType,
    })
  },
  goReservation() {
    console.log(this.data.corpCredit)
    if (this.data.reservationNumber > 10) {
      wx.showToast({
        title: '最多可预约10家企业',
        icon: 'none'
      })
      return
    }

    const params = {
      corpCredit: this.data.corpCredit,
      batchNum: this.data.batchNum
    }
    console.log(params, 'paramsparams')
    getApp().globalData.request(
      '/corpVisit/LaborCompetition', params,
      "POST"
    ).then(res => {
      console.log(res, '预约了')
      if (res.code == 200) {
        wx.showToast({
          title: '预约走访成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }

    })
  },
  goKcDetail(e) {
    wx.navigateTo({
      url: `/packageA/pages/homelink/innovation_score_detail/innovation_score_detail?corpKey=${e.currentTarget.dataset.id}&shortName=${e.currentTarget.dataset.name}`
    });
  },
  topcheck(e) {
    console.log(e.currentTarget.dataset.type, 'eee')
    this.setData({
      listType: e.currentTarget.dataset.type,
      list: [],
      pageNum: 1
    })
    this.getList()
  },
  toClose() {
    this.setData({
      isSx: false
    })
  },
  goback() {
    wx.navigateBack({
      delta: 1
    })
  },
  NOyyzfBtn() {
    this.setData({
      NOyyzf: false
    })
  },
  reservation(e) {
    console.log(e, 'ee')
    let corpRole = wx.getStorageSync('userInfo').corpRole
    console.log(corpRole, 'corpRolecorpRole')
    if (corpRole.includes('cbrc') || corpRole.includes('fir_admin')) {
      // wx.showToast({
      //   title: '管理员无需进行抢单走访',
      //   icon: 'none'
      // })
      // this.setData({
      //   NOyyzf:true
      // })
      Dialog.alert({
        message: '管理员无需进行抢单走访',
      }).then(() => {
        // on close
      });
    } else {
      getApp().globalData.request(
        '/corpVisit/queryLaborCount', {},
        "POST"
      ).then(res => {
        console.log(res, '预约了')
        this.setData(({
          reservationNumber: res.data + 1,
          isSx: true,
          corpCredit: e.currentTarget.dataset.proitem.corpKey,
          batchNum: e.currentTarget.dataset.proitem.batchNum
        }))
      })
    }

    return
    let isAgencyCode = wx.getStorageSync('userInfo').agencyCode
    console.log(isAgencyCode, 'isAgencyCode')
    if (isAgencyCode) {
      const corpkey = e.currentTarget.dataset.proitem.corpKey
      const distance = e.currentTarget.dataset.proitem.distance
      const userId = wx.getStorageSync('userInfo').userId
      console.log(distance, 'eeee')
      const params = {
        corpCredit: corpkey,
        userId: userId,
        createTime: '',
        belongTo: '',
        distance: distance,
        userLat: this.transMarker([this.data.latitude, this.data.longitude])[0],
        userLng: this.transMarker([this.data.latitude, this.data.longitude])[1],
      }
      console.log(params, 'paramsv')
      getApp().globalData.request(
        '/corpVisit/seize_orders', params,
        "POST"
      ).then(res => {
        console.log(res, 'eee')
        let msg = res.msg
        let code = res.code
        wx.navigateTo({
          url: `/pages/appointmentResults/appointmentResults?msg=${msg}&code=${code}`,
        });
      })
    } else {
      wx.navigateTo({
        url: '/packageA/pages/notBind/notBind?type=3'
      })
    }
  },
  searchInput(e) {
    this.setData({
      searchValue: e.detail,

    })
    console.log(this.data.searchValue)
  },
  goSearch() {
    this.setData({
      list: [],
      pageNum: 1,
    })
    this.getList()
  },
  getList() {
    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      corpName: this.data.searchValue,
      ...this.data.searchObj
    }
    console.log(params, this.data.labelList, '请求参数')
    getApp().globalData.request(
      '/corpVisit/labor_order_corp', params,
      "POST"
    ).then(res => {
      console.log(res, '列表')
      this.setData({
        total: res.data.total,
        loading: false
      })
      if (res.data.list.length > 0) {
        // 距离保留整数
        res.data.list.forEach(function (item, index) {
          if (item.shortName) {
            item.shortName1 = item.shortName.slice(0, 2)
            item.shortName2 = item.shortName.slice(2, 4)
          }
        });

        const list = this.data.list.concat(res.data.list)
        // 设置标题颜色 
        for (let i in list) {
          if (i % 4 === 0) {
            list[i].backColor = '#8BCBB8'
          } else if (i % 3 === 0) {
            list[i].backColor = '#99C1F2'
          } else if (i % 5 === 0) {
            list[i].backColor = '#B8AAD6'
          } else {
            list[i].backColor = '#D99D9A'
          }
        }
        this.setData({
          list: list,
        })
      } else {
        this.setData({
          total: res.data.totalm,
          loading: false
        })
      }
    })
  },
  details(e) {
    console.log(e)
    const corpKey = e.currentTarget.dataset.proitem.corpKey
    const latitude = e.currentTarget.dataset.proitem.latitude
    const longitude = e.currentTarget.dataset.proitem.longitude
    const distance = e.currentTarget.dataset.proitem.distance
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${corpKey}&latitude=${latitude}&longitude=${longitude}&distance=${distance}`,
    });
  },
  scrollBottom() {
    console.log(this.data.list.length, this.data.total, '判断')
    if (this.data.list.length < this.data.total) {
      // this.onBottom();
      console.log(this.data.list.length, this.data.total, '11')

      this.setData({
        pageNum: ++this.data.pageNum,
      });
      this.getList();
    }
  },
  phone(event) {
    console.log(event);
    if (event.currentTarget.datagiset.phone) {
      wx.makePhoneCall({
        phoneNumber: event.currentTarget.dataset.phone,
      });
    } else {
      wx.showToast({
        icon: "none",
        title: "暂无电话",
      });
    }
  },
  // 坐标系转化
  transMarker(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },
  location(e) {
    console.log(e)
    const latitude = e.currentTarget.dataset.proitem.latitude
    const longitude = e.currentTarget.dataset.proitem.longitude
    const name = e.currentTarget.dataset.proitem.d2CorpName
    const address = e.currentTarget.dataset.proitem.d2Dom
    const scale = e.currentTarget.dataset.proitem.scale
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: name,
      address: address,
      scale: scale,
    });
    // wx.getLocation({
    //   type: 'wgs84',
    //   success(res) {

    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面加载f
   */
  onLoad() {

    //获取系统信息， 状态栏高度为 sysInfo['statusBarHeight'];
    let sysInfo = wx.getSystemInfoSync();
    // 胶囊信息
    let menu = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度
    let navBarHeight = (menu.top - sysInfo.statusBarHeight) * 2 + menu.height;
    this.setData(({
      statusBarHeight: sysInfo.statusBarHeight,
      navBarHeight: navBarHeight,
      loading: true
    }))
    console.log(navBarHeight, 'navBarHeight');
    let that = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log('纬度' + res.latitude)
        console.log('经度' + res.longitude)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          list: [],
          total: ''
        })
        that.getList()
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.needFresh) {
      const js_filter = wx.getStorageSync('js_filter')
      // 获取筛选条件
      let labelList = []
      let obj = {}
      js_filter.forEach(pre => {
        if (pre.title === '科创评分') {
          obj.kcScoreMin = pre.startScore
          obj.kcScoreMax = pre.endScore
          if (obj.kcScoreMax) {
            labelList.push(`科创评分：${obj.kcScoreMin}-${obj.kcScoreMax}`)
          }
        } else if (pre.title === '征信评分') {
          obj.creditScoreMin = pre.startScore
          obj.creditScoreMax = pre.endScore
          if (obj.creditScoreMax) {
            labelList.push(`征信评分：${obj.creditScoreMin}-${obj.creditScoreMax}`)
          }
        } else {
          obj[pre.key] = pre.multiple ? pre.value : pre.value[0]
          if (pre.multiple) {
            if (pre.value.length > 0) {
              labelList.push(`${pre.title}：${pre.value.join('、')}`)
            }
          } else {
            if (pre.title === '距离排序') {
              if (pre.value.length > 0) {
                labelList.push(`${pre.title}：${pre.value[0] === '1' ? '距离较近' : '不限距离'}`)
              }
            } else {
              if (pre.value.length > 0) {
                labelList.push(`${pre.title}：${pre.value[0]}`)
              }
            }
          }
        }
      })
      this.setData({
        labelList: labelList,
        searchObj: obj,
        list: [],
        total: 0,
        pageNum: 1
      })
      this.setData({
        loading: true
      })
      this.getList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})